<template>
  <div>
    <el-input v-model="input" placeholder="请输入书名进行查找" clearable style="width: 500px"/>
    <el-button type="primary" class="ml5" style="margin-left: 10px" @click="searchData">
      <el-icon style="vertical-align: middle">
        <Search/>
      </el-icon>
      <span style="vertical-align: middle"
            v-loading.fullscreen.lock="fullscreenLoading"> 搜索 </span>
    </el-button>

    <el-button type="success" class="ml5" @click="addData">
      <el-icon style="vertical-align: middle">
        <Plus/>
      </el-icon>
      <span style="vertical-align: middle"> 新增 </span>
    </el-button>

    <el-table :data="bookList" style="width: 700px">
      <el-table-column prop="id" label="编号" width="100px"/>
      <el-table-column prop="name" label="书名" width="500px"/>
      <el-table-column
          fixed="right"
          header-align="center"
          align="center"
          width="300px"
          label="操作">
        <template #default="scope">
          <el-button type="danger" class="ml5" @click="removeData(scope.row)">
            <el-icon style="vertical-align: middle">
              <Remove/>
            </el-icon>
            <span style="vertical-align: middle"> 删除 </span>
          </el-button>

          <el-button type="warning" class="ml5" @click="updateData(scope.row)">
            <el-icon style="vertical-align: middle">
              <Edit/>
            </el-icon>
            <span style="vertical-align: middle"> 修改 </span>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-button @click="logOut">退出登录</el-button>

    <el-dialog v-model="dialogFormVisible" :title="dialogTitle===1?'修改':'新增'">
      <el-form :model="bookForm">
        <el-form-item label="编号" label-width="120px">
          <el-input v-model="bookForm.id" autocomplete="off" disabled/>
        </el-form-item>
        <el-form-item label="书名" label-width="120px">
          <el-input v-model="bookForm.name" placeholder="请输入书名"/>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAddOrUpdate">
          确认
        </el-button>
      </span>
      </template>
    </el-dialog>

    <!--  确认删除框  -->
    <el-dialog
        v-model="deleteVisible"
        title="删除"
        width="30%"
        :before-close="handleClose"
    >
      <span>是否确认删除？</span>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="deleteVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRemove">
          确认
        </el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import {defineComponent, reactive, ref} from 'vue';
import {useRouter} from "vue-router";
import {ElMessage, ElMessageBox, ElLoading} from "element-plus";
import useUser from '@/stores/user.js'
import request from "@/utils/request.js";

export default defineComponent({
  name: '',
  components: {},
  setup() {
    let deleteVisible = ref();
    // 为1则是修改，为0则是新增
    let dialogTitle = ref();
    let dialogFormVisible = ref(false);
    // 加载界面
    const fullscreenLoading = ref(false)

    const userStore = useUser();
    // 页面跳转
    const router = useRouter();

    let bookForm = reactive({
      id: null,
      name: ""
    })

    let input = ref('');

    let bookList = reactive(userStore.userInfo.bookDtoList);

    let getData = () => {
      fullscreenLoading.value = true;
      request.get('/user/' + userStore.userInfo.id).then((res) => {
        console.log("getData--res:", res);
        if (res.code === 0) {
          bookList.length = 0
          for (let i = 0; i < res.data.bookDtoList.length; i++) {
            bookList.push(res.data.bookDtoList[i])
          }
          fullscreenLoading.value = false;
        } else if (res.code === 400) {
          ElMessage({
            message: `${res.msg}`,
            type: 'error',
          })
          fullscreenLoading.value = false;
        }
      }).catch((err) => {
        console.log("err:", err);
        ElMessage({
          message: '出现错误，请重试',
          type: 'error',
        })
      })
    }

    getData();

    function logOut() {
      localStorage.removeItem('token')
      router.push("/login");
      ElMessage({
        message: '退出登陆成功',
        type: 'success',
      })
    }

    // 即将删除的数据
    let needToDoData = reactive({})

    function removeData(value) {
      deleteVisible.value = true;
      needToDoData = value;
      console.log("删除:", value);
    }

    // 确认删除
    function confirmRemove() {
      fullscreenLoading.value = true;
      request.delete('/user/remove-book/' + needToDoData.id, {}).then((res) => {
        console.log("res:", res);
        if (res.code === 0) {
          fullscreenLoading.value = false;
          deleteVisible.value = false;
          ElMessage({
            message: '删除成功',
            type: 'success',
          })
          // 删除成功，重新获取数据
          getData();
        }
      }).catch((err) => {
        console.log("err:", err);
      })
    }

    function updateData(value) {
      dialogTitle.value = 1;
      dialogFormVisible.value = true;
      bookForm.id = value.id;
      bookForm.name = value.name;
      // 需要更新的数据
      needToDoData.id = value.id;
      console.log("修改:", value);
    }

    function addData(value) {
      dialogTitle.value = 0;
      // 重置对话框记录
      bookForm.id = null;
      bookForm.name = '';
      dialogFormVisible.value = true;
      console.log("新增:", value);
    }

    // 确认新增或更新
    function confirmAddOrUpdate() {
      if (dialogTitle.value === 1) {
        // 修改
        // 需要更新的数据
        needToDoData.id = bookForm.id;
        needToDoData.name = bookForm.name;
        console.log("需要修改的数据:", needToDoData);
        fullscreenLoading.value = true;
        request.post('/user/update-book', {
          id: needToDoData.id,
          name: needToDoData.name,
          userId: userStore.userInfo.id
        }).then((res) => {
          console.log("res:", res);
          if (res.code === 0) {
            fullscreenLoading.value = false;
            ElMessage({
              message: '更新成功',
              type: 'success',
            })
            dialogFormVisible.value = false;
            // 重新获取数据
            getData();
          }
        }).catch((err) => {
          console.log("err:", err);
        })
      } else if (dialogTitle.value === 0) {
        // 新增
        // 需要更新的数据
        needToDoData.name = bookForm.name;
        console.log("需要新增的数据:", needToDoData);
        fullscreenLoading.value = true;
        request.post('/user/add-book', {
          name: needToDoData.name,
          userId: userStore.userInfo.id
        }).then((res) => {
          console.log("res:", res);
          if (res.code === 0) {
            fullscreenLoading.value = false;
            ElMessage({
              message: '新增成功',
              type: 'success',
            })
            dialogFormVisible.value = false;
            // 重新获取数据
            getData();
          }
        }).catch((err) => {
          console.log("err:", err);
        })
      } else {
        console.log("既不是修改，也不是新增");
      }
    }

    function searchData() {
      fullscreenLoading.value = true;
      console.log("input:", input.value);
      if (input.value === null || input.value.trim() === '' || input.value.length === 0) {
        // 查找全部
        getData();
      } else {
        // 根据书名查找
        request.get('/user/getBookByBookName/' + input.value).then((res) => {
          if (res.code === 0) {
            console.log("searchData:", res);
            fullscreenLoading.value = false;
            bookList.length = 0
            for (let i = 0; i < res.data.length; i++) {
              bookList.push(res.data[i])
            }
          }
        }).catch((err) => {
          console.log("err:", err);
        })
      }
    }

    const handleClose = (done: () => void) => {
      ElMessageBox.confirm('确定关闭对话框吗?')
          .then(() => {
            done()
          })
          .catch(() => {
            // catch error
          })
    }

    return {
      logOut,
      removeData,
      updateData,
      addData,
      searchData,
      handleClose,
      confirmRemove,
      confirmAddOrUpdate,
      // 关键词查找
      input,
      bookList,
      dialogFormVisible,
      bookForm,
      dialogTitle,
      deleteVisible,
      fullscreenLoading
    }
  }
})
</script>
<style scoped>

</style>
